<?php

namespace App\Containers\AppSection\Confirmation\Actions;

use App\Containers\AppSection\Confirmation\Models\Confirmation;
use App\Containers\AppSection\Confirmation\Tasks\CreateConfirmationTask;
use App\Containers\AppSection\Confirmation\Tasks\DeleteAllConfirmsByValueTask;
use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Ship\Parents\Actions\Action;
use App\Ship\Parents\Requests\Request;
use App\Ship\Phones\SmsRu;

class SendProfilePhoneCodeAction extends Action
{
    public function run(Request $request): Confirmation
    {
        $code = generateRandomInt(config('appSection-confirmation.code-length'));

        app(DeleteAllConfirmsByValueTask::class)
            ->run($request->profile()->phone, $request->getInputByKey('type'), config('appSection-confirmation.confirms.phone.type'));

        $confirmation = app(CreateConfirmationTask::class)
            ->run([
                'code' => $code,
                'value' => $request->profile()->phone,
                'request_type' => $request->getInputByKey('type'),
                'confirm_type' => config('appSection-confirmation.confirms.phone.type'),
            ]);

        try {
            SmsRu::create($code)->to($request->profile()->phone)->send();
        } catch (\Throwable $e) {

        }

        app(CreateLogTask::class)->run($request->profile()->id, 'Отправка кода для смены номера телефона', 'confirmation');

        return $confirmation;
    }
}
